//
//  download.m
//  download
//
//  Created by lanou3g on 15/10/16.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "download.h"

@interface download ()

@property(nonatomic,strong)AFHTTPRequestOperation *operation;

@end


@implementation download
//下载封装
-(void)downloadFileWithOption:(NSDictionary *)paramDic withURL:(NSString *)requestURL savePath:(NSString *)savedPath downloadSuccess:(void(^)(AFHTTPRequestOperation *operation,id responseObject))success downloadFailure:(void(^)(AFHTTPRequestOperation *operation,NSError *error))failure progress:(void(^)(float progress))progress{
    
    AFHTTPRequestSerializer *serializer =[AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request =[serializer requestWithMethod:@"GET" URLString:requestURL parameters:paramDic error:nil];
    _operation =[[AFHTTPRequestOperation alloc]initWithRequest:request];
    
    [_operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savedPath append:NO]];
    [_operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        float p =(float)totalBytesRead/totalBytesExpectedToRead;
        progress(p);
                NSLog(@"download:%f",(float)totalBytesRead/totalBytesExpectedToRead);
    }];
    [_operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        success(operation,responseObject);
        NSLog(@"下载成功");
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        failure(operation,error);
        NSLog(@"下载失败");
    }];
    [_operation start];
}


//停止操作
-(void)pauseOperation{
    if (_operation.isExecuting) {
        [_operation pause];
    }
}
//继续下载
-(void)resumeOperation{
    if (_operation.isPaused) {
        [_operation resume];
    }
}

//取消操作
-(void)cancelOperation{
    [_operation cancel];
}


@end
